<template>
  <div class="student-list">
    <div class="page-title">学生管理</div>
    
    <!-- 搜索表单 -->
    <a-card class="search-form mb-16">
      <a-form
        ref="searchFormRef"
        :model="searchForm"
        layout="inline"
        @finish="handleSearch"
      >
        <a-form-item label="学生姓名" name="name">
          <a-input
            v-model:value="searchForm.name"
            placeholder="请输入学生姓名"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="学号" name="studentId">
          <a-input
            v-model:value="searchForm.studentId"
            placeholder="请输入学号"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="班级" name="classId">
          <a-select
            v-model:value="searchForm.classId"
            placeholder="请选择班级"
            allow-clear
            style="width: 150px"
          >
            <a-select-option
              v-for="cls in classList"
              :key="cls.id"
              :value="cls.id"
            >
              {{ cls.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="状态" name="status">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="active">在读</a-select-option>
            <a-select-option value="graduated">已毕业</a-select-option>
            <a-select-option value="transferred">已转学</a-select-option>
            <a-select-option value="suspended">休学</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit" :loading="loading">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
    
    <!-- 操作按钮 -->
    <div class="action-buttons mb-16">
      <a-space>
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          添加学生
        </a-button>
        
        <a-button
          type="primary"
          ghost
          :disabled="!selectedRowKeys.length"
          @click="handleBatchDelete"
        >
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
        
        <a-button @click="handleImport">
          <template #icon>
            <ImportOutlined />
          </template>
          导入学生
        </a-button>
        
        <a-button @click="handleExport">
          <template #icon>
            <ExportOutlined />
          </template>
          导出学生
        </a-button>
      </a-space>
    </div>
    
    <!-- 学生列表表格 -->
    <a-card class="data-table">
      <a-table
        :columns="columns"
        :data-source="studentList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
      >
        <!-- 头像列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar :size="40">
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
          </template>
          
          <!-- 性别列 -->
          <template v-else-if="column.key === 'gender'">
            <a-tag :color="record.gender === 'M' ? 'blue' : 'pink'">
              {{ record.gender === 'M' ? '男' : '女' }}
            </a-tag>
          </template>
          
          <!-- 年龄列 -->
          <template v-else-if="column.key === 'age'">
            {{ calculateAge(record.birthDate) }}岁
          </template>
          
          <!-- 状态列 -->
          <template v-else-if="column.key === 'status'">
            <a-tag
              :color="getStatusColor(record.status)"
              class="status-tag"
            >
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleView(record)">
                查看
              </a-button>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这个学生吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  DeleteOutlined,
  ImportOutlined,
  ExportOutlined,
  UserOutlined
} from '@ant-design/icons-vue'
import { studentApi } from '@/api'
import dayjs from 'dayjs'

const router = useRouter()

// 表单引用
const searchFormRef = ref()

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  studentId: '',
  classId: undefined,
  status: undefined
})

// 选中的行
const selectedRowKeys = ref([])

// 班级列表
const classList = ref([
  { id: 'class1', name: '一年级1班' },
  { id: 'class2', name: '一年级2班' },
  { id: 'class3', name: '二年级1班' },
  { id: 'class4', name: '二年级2班' },
  { id: 'class5', name: '三年级1班' },
  { id: 'class6', name: '三年级2班' }
])

// 学生列表
const studentList = ref([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列配置
const columns = [
  {
    title: '头像',
    key: 'avatar',
    width: 80,
    align: 'center'
  },
  {
    title: '学号',
    dataIndex: 'studentId',
    key: 'studentId',
    width: 120
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100
  },
  {
    title: '性别',
    key: 'gender',
    width: 80,
    align: 'center'
  },
  {
    title: '年龄',
    key: 'age',
    width: 80,
    align: 'center'
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 130
  },
  {
    title: '班级',
    dataIndex: 'className',
    key: 'className',
    width: 120
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '入学日期',
    dataIndex: 'enrollmentDate',
    key: 'enrollmentDate',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}))

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    active: 'green',
    graduated: 'blue',
    transferred: 'orange',
    suspended: 'red'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    active: '在读',
    graduated: '已毕业',
    transferred: '已转学',
    suspended: '休学'
  }
  return statusMap[status] || '未知'
}

// 计算年龄
const calculateAge = (birthDate) => {
  if (!birthDate) return '-'
  return dayjs().diff(dayjs(birthDate), 'year')
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadStudentList()
}

// 重置搜索
const handleReset = () => {
  searchFormRef.value.resetFields()
  pagination.current = 1
  loadStudentList()
}

// 添加学生
const handleAdd = () => {
  router.push('/students/add')
}

// 查看学生
const handleView = (record) => {
  router.push(`/students/view/${record.id}`)
}

// 编辑学生
const handleEdit = (record) => {
  router.push(`/students/edit/${record.studentId}`)
}

// 删除学生
const handleDelete = async (record) => {
  try {
    await studentApi.deleteStudent(record.studentId)
    message.success('删除成功')
    loadStudentList()
  } catch (error) {
    console.error('删除学生失败:', error)
    message.error(error.message || '删除失败')
  }
}

// 批量删除
const handleBatchDelete = () => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个学生吗？`,
    onOk: async () => {
      try {
        await studentApi.batchDeleteStudents(selectedRowKeys.value)
        message.success('批量删除成功')
        selectedRowKeys.value = []
        loadStudentList()
      } catch (error) {
        console.error('批量删除失败:', error)
        message.error(error.message || '批量删除失败')
      }
    }
  })
}

// 导入学生
const handleImport = () => {
  message.info('导入功能开发中...')
}

// 导出学生
const handleExport = () => {
  message.info('导出功能开发中...')
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadStudentList()
}

// 加载学生列表
const loadStudentList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = {
      current: pagination.current,
      size: pagination.pageSize
    }
    
    // 添加搜索条件
    if (searchForm.name) {
      params.name = searchForm.name
    }
    if (searchForm.studentId) {
      params.studentId = searchForm.studentId
    }
    if (searchForm.classId) {
      params.classId = searchForm.classId
    }
    if (searchForm.status) {
      params.status = searchForm.status
    }
    
    // 调用分页查询API
    const response = await studentApi.getStudentPage(params)
    
    // 更新数据
    studentList.value = response.records || []
    pagination.total = response.total || 0
    pagination.current = response.current || 1
    pagination.pageSize = response.size || 10
    
  } catch (error) {
    console.error('加载学生列表失败:', error)
    message.error(error.message || '加载学生列表失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadStudentList()
})
</script>

<style scoped>
.student-list {
  padding: 0;
}

.search-form {
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.data-table {
  border-radius: 8px;
}

.status-tag {
  border-radius: 12px;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .ant-btn {
    width: 100%;
  }
}
</style>